package com.online.usermanagesystem.utils;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ConcurrentLRUMap<K, V> {

    private int max;
    private ReentrantReadWriteLock lock;
    private LinkedHashMap<K, V> map;

    public ConcurrentLRUMap(int max) {

        this.max = max;
        lock = new ReentrantReadWriteLock();

        int capacity = (int) Math.ceil(max / 0.75f) + 1;
        map = new LinkedHashMap<K, V>(capacity, 0.75f, true) {

            @Override
            protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
                return size() > max;
            }
        };
    }

    public void put(K key, V value) {
        lock.writeLock().lock();

        map.put(key, value);

        lock.writeLock().unlock();
    }

    public V remove(K key) {
        return map.remove(key);
    }

    public V get(K key) {
        V obj;
        lock.readLock().lock();

        obj = map.get(key);

        lock.readLock().unlock();

        return obj;
    }

    @Override
    public String toString() {
        return map.toString();
    }
}
